package org.yscz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.yscz.common.Constants;
import org.yscz.entity.*;
import org.yscz.entity.vo.QuestionVo;
import org.yscz.entity.vo.ScaleScoreVo;
import org.yscz.entity.vo.ScaleTypeVo;
import org.yscz.entity.vo.ScaleVo;
import org.yscz.mapper.*;
import org.yscz.service.ScaleService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author muqs
 * @create 2021-08-19 17:48
 */
@Service
@Slf4j
public class ScaleServiceImpl extends ServiceImpl<ScaleMapper, Scale> implements ScaleService {

    @Autowired
    private ScaleMapper scaleMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private OptionMapper optionMapper;

    @Autowired
    private OptionServiceImpl optionServic;

    @Autowired
    private QuestionServiceImpl questionService;

    @Autowired
    private ScoreMapper scoreMapper;

    @Autowired
    private AlgMapper algMapper;

    @Autowired
    private FactorMapper factorMapper;

    @Autowired
    private QuestionFactorMapper questionFactorMapper;

    @Autowired
    private ScaleAlgMapper scaleAlgMapper;

    @Autowired
    private ScaleProjectMapper scaleProjectMapper;

    @Override
    public Scale add(ScaleVo scaleVo) {
        Scale scale = new Scale();
        if (scaleVo != null) {
            BeanUtils.copyProperties(scaleVo, scale);
            scale.setUpdateTime(new Date());
            scaleMapper.insert(scale);

            List<Score> scores = scaleVo.getScoreList();

            if (!CollectionUtils.isEmpty(scores)) {
                scores.stream().forEach(item -> {
                    item.setScaleIdFk(scale.getScaleId());
                    scoreMapper.insert(item);
                });
            }
        }
        return scale;
    }

    @Override
    public void modify(ScaleVo scaleVo) {

        Scale scale = new Scale();
        if (scaleVo != null) {
            BeanUtils.copyProperties(scaleVo, scale);
            scale.setUpdateTime(new Date());
            scaleMapper.updateById(scale);

            // 先将量表分数数据删除，然后重新插入
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("scale_id_fk", scaleVo.getScaleId());
            scoreMapper.delete(queryWrapper);

            List<Score> scores = scaleVo.getScoreList();
            if (!CollectionUtils.isEmpty(scores)) {
                scores.stream().forEach(item -> {
                    item.setScaleIdFk(scaleVo.getScaleId());
                    scoreMapper.insert(item);
                });
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(Long scaleId) {
        scaleMapper.deleteById(scaleId);

        // 查询量表对应题目数据
        QueryWrapper questionWrapper = new QueryWrapper();
        questionWrapper.eq("scale_id_fk", scaleId);
        List<Question> questions = questionMapper.selectList(questionWrapper);

        if (!CollectionUtils.isEmpty(questions)) {
            List<Long> questionIds = new ArrayList<>();
            questions.stream().forEach(item -> {
                questionIds.add(item.getQuestionId());
            });

            // 删除题目数据
            questionMapper.deleteBatchIds(questionIds);
            // 删除题目选项数据
            QueryWrapper optionWrapper = new QueryWrapper();
            optionWrapper.in("question_id_fk", questionIds);
            optionMapper.delete(optionWrapper);

            // 删除分数数据
            QueryWrapper scoreWrapper = new QueryWrapper();
            scoreWrapper.in("scale_id_fk", scaleId);
            scoreMapper.delete(scoreWrapper);
        }
    }

    @Override
    public IPage<Scale> listPage(QueryWrapper queryWrapper, IPage<Scale> page) {
        return scaleMapper.selectPage(page, queryWrapper);
    }

    @Override
    public IPage<ScaleVo> listPageByCondition(IPage<Scale> page, Map condition) {
        return scaleMapper.listPageByCondition(page, condition);
    }

    @Override
    public void questionAdd(List<QuestionVo> questionVoList) {
        List<Option> options = new ArrayList<>();
        questionVoList.stream().forEach(item -> {
            // 题目信息入库
            Question question = new QuestionVo();
            BeanUtils.copyProperties(item, question);
            questionMapper.insert(question);

            // 处理题目选项信息
            if (!CollectionUtils.isEmpty(item.getOptionList())) {
                item.getOptionList().stream().forEach(option -> {
                    option.setQuestionIdFk(question.getQuestionId());
                    options.add(option);
                });
            }
        });

        // 选项信息入库
        if (!CollectionUtils.isEmpty(options)) {
            optionServic.saveBatch(options);
        }
    }

    @Override
    public void questionModify(List<QuestionVo> questionVoList) {
        List<Option> options = new ArrayList<>();
        List<Question> questions = new ArrayList<>();
        questionVoList.stream().forEach(item -> {
            // 更新试题信息
            Question question = new QuestionVo();
            BeanUtils.copyProperties(item, question);
            questions.add(question);

            // 处理试题选项信息
            if (!CollectionUtils.isEmpty(item.getOptionList())) {
                item.getOptionList().stream().forEach(option -> {
                    options.add(option);
                });
            }
        });

        // 更新题目信息
        if (!CollectionUtils.isEmpty(questions)) {
            questionService.saveOrUpdateBatch(questions);
        }

        // 更新选项信息
        if (!CollectionUtils.isEmpty(options)) {
            optionServic.saveOrUpdateBatch(options);
        }
    }

    @Override
    public List<QuestionVo> queryByScaleId(Long scaleId) {
        List<QuestionVo> questionVos = questionMapper.queryByScaleId(scaleId);
        List<QuestionVo> questionVoList = new ArrayList<>();
        for (QuestionVo questionVo : questionVos) {
            QueryWrapper<QuestionFactor> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("question_id",questionVo.getQuestionId());
            List<QuestionFactor> questionFactors = questionFactorMapper.selectList(queryWrapper);
            for (QuestionFactor questionFactor : questionFactors) {
                QueryWrapper<Factor> factorWrapper = new QueryWrapper<>();
                factorWrapper.eq("factor_id",questionFactor.getFactorId());
                Factor factor = factorMapper.selectOne(factorWrapper);

                QueryWrapper<Alg> algWrapper = new QueryWrapper<>();
                algWrapper.eq("alg_id",factor.getAlgIdFk());
                Alg alg = algMapper.selectOne(algWrapper);
                if ("因子分".equals(alg.getAlgName())){
                    questionVo.setFactorId(factor.getFactorId());
                }
                if ("正反".equals(alg.getAlgName())){
                    questionVo.setProAndConFactorId(factor.getFactorId());
                }
            }
            questionVoList.add(questionVo);
        }
        return questionVoList;
    }

    @Override
    public ScaleVo queryScaleDetail(Long scaleId) {
        return scaleMapper.queryDetailById(scaleId);
    }

    @Override
    public List<ScaleVo> listPageByConditionByProject(Long projectId, Integer pageNum, Integer pageSize, Map condition) {
        Integer startPageNum = (pageNum - 1) * pageSize;
        return scaleMapper.listPageByConditionAndProject(projectId, startPageNum, pageSize, condition);
    }

    @Override
    public JSONObject addScale(ScaleScoreVo scaleScoreVo) {
        Scale scale = new Scale();
        //因子信息列表
        List<Factor> factorList = new ArrayList<>();
        //正反信息列表
        Set<Factor> proAndConSet = new HashSet<>();
        //计算规则
        ScaleAlg scaleAlg = new ScaleAlg();
        if (scaleScoreVo != null) {
            BeanUtils.copyProperties(scaleScoreVo, scale);
            scale.setUpdateTime(new Date());
            scaleMapper.insert(scale);

            //总分
            List<Score> totalScore = scaleScoreVo.getTotalScore();
            addFactorAndRuleAndCalculationRules(Constants.TOTAL_SCORE_TYPE, totalScore, scale, scaleAlg, scaleScoreVo);

            //因子分
            List<Score> factorScore = scaleScoreVo.getFactorScore();
            addFactorAndRuleAndCalculationRules(Constants.FACTOR_SCORE_TYPE, factorScore, scale, scaleAlg, scaleScoreVo);
            //遍历factorScore，添加因子信息返给前台
            Iterator<Score> factorIterator = factorScore.iterator();
            while (factorIterator.hasNext()) {
                Score score = factorIterator.next();
                Long factorIdFk = score.getFactorIdFk();
                Factor factor = factorMapper.selectById(factorIdFk);
                factorList.add(factor);
            }

            //正反分
            List<Score> proAndConScore = scaleScoreVo.getProAndConScore();
            addFactorAndRuleAndCalculationRules(Constants.POSITIVE_AND_NEGATIVE_SCORE_TYPE, proAndConScore, scale, scaleAlg, scaleScoreVo);
            //遍历proAndConScore，添加正反因子信息返给前台
            Iterator<Score> proAndConIterator = proAndConScore.iterator();
            while (proAndConIterator.hasNext()) {
                Score score = proAndConIterator.next();
                Long factorIdFk = score.getFactorIdFk();
                Factor factor = factorMapper.selectById(factorIdFk);
                proAndConSet.add(factor);
            }

            //阴阳分
            List<Score> lunisolarScore = scaleScoreVo.getLunisolarScore();
            addFactorAndRuleAndCalculationRules(Constants.SUN_AND_SHADE_SCORE_TYPE, lunisolarScore, scale, scaleAlg, scaleScoreVo);

            //计算规则入t_question_dactor
            //CalculationRules calculationRules = scaleScoreVo.getCalculationRules();

            //添加到量表行业关联表
            ScaleProject scaleProject = new ScaleProject().setProjectId(scaleScoreVo.getProjectId()).setScaleId(scale.getScaleId());
            scaleProjectMapper.insert(scaleProject);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("scale", scale);
        jsonObject.put("factorScore", factorList);
        jsonObject.put("proAndConScore", proAndConSet);
        return jsonObject;
    }

    @Override
    public JSONObject updateScale(ScaleScoreVo scaleScoreVo) {
        Scale scale = new Scale();
        if (scaleScoreVo != null) {
            BeanUtils.copyProperties(scaleScoreVo, scale);
            scale.setUpdateTime(new Date());
            //修改量表信息
            scaleMapper.updateById(scale);
            log.info("update scale:[{}]", scale);

            //修改规则，先将量表分数数据删除，然后重新插入
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("scale_id_fk", scaleScoreVo.getScaleId());
            scoreMapper.delete(queryWrapper);
            //重新插入规则
            //总分
            List<Score> totalScores = scaleScoreVo.getTotalScore();
            QueryWrapper<Alg> algTotalWrapper = new QueryWrapper<>();
            algTotalWrapper.eq("alg_name", "总分");
            Alg algTotal = algMapper.selectOne(algTotalWrapper);
            //因子表不删除，如果跟之前的不一样只添加
            addFactorAndRule(totalScores, algTotal, scale);

            //因子分
            List<Score> factorScores = scaleScoreVo.getFactorScore();
            QueryWrapper<Alg> algFactorWrapper = new QueryWrapper<>();
            algFactorWrapper.eq("alg_name", "因子分");
            Alg algFactor = algMapper.selectOne(algFactorWrapper);
            //因子表不删除，如果跟之前的不一样只添加
            addFactorAndRule(factorScores, algFactor, scale);

            //正反分
            List<Score> posAndNegScores = scaleScoreVo.getProAndConScore();
            QueryWrapper<Alg> algPosAndNegWrapper = new QueryWrapper<>();
            algPosAndNegWrapper.eq("alg_name", "正反");
            Alg algPosAndNeg = algMapper.selectOne(algPosAndNegWrapper);
            //因子表不删除，如果跟之前的不一样只添加
            addFactorAndRule(posAndNegScores, algPosAndNeg, scale);

            //阴阳分
            List<Score> sunAndShadeScores = scaleScoreVo.getLunisolarScore();
            QueryWrapper<Alg> algSunAndShadeWrapper = new QueryWrapper<>();
            algSunAndShadeWrapper.eq("alg_name", "阴阳");
            Alg algSunAndShade = algMapper.selectOne(algSunAndShadeWrapper);
            //因子表不删除，如果跟之前的不一样只添加
            addFactorAndRule(sunAndShadeScores, algSunAndShade, scale);


            //根据量表id去量表算法表（t_scale_alg）查询出量表对应的数据，修改计算规则
            QueryWrapper<ScaleAlg> scaleAlgQueryWrapper = new QueryWrapper<>();
            scaleAlgQueryWrapper.eq("scale_id_fk", scale.getScaleId());
            List<ScaleAlg> scaleAlgs = scaleAlgMapper.selectList(scaleAlgQueryWrapper);
            //修改计算规则
            CalculationRules calculationRules = scaleScoreVo.getCalculationRules();
            if (!CollectionUtils.isEmpty(scaleAlgs)) {
                scaleAlgs.stream().forEach(scaleAlg -> {
                    //总分计算规则更新
                    if (Constants.SCALE_ALG_TOTAL.equals(scaleAlg.getFactorName())) {
                        scaleAlg.setOperator(calculationRules.getTotalScoreRule());
                    } else if (Constants.SCALE_ALG_FACTOR.equals(scaleAlg.getFactorName())) {
                        scaleAlg.setOperator(calculationRules.getFactorScoreRule());
                    } else if (Constants.SCALE_ALG_POS_AND_NEG.equals(scaleAlg.getFactorName())) {
                        scaleAlg.setOperator(calculationRules.getProAndConScoreRule());
                    } else {
                        scaleAlg.setOperator(calculationRules.getLunisolarScoreRule());
                    }
                    scaleAlgMapper.updateById(scaleAlg);
                });
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("scale", scale);
        return jsonObject;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delScale(Long scaleId) {
        scaleMapper.deleteById(scaleId);

        // 查询量表对应题目数据
        QueryWrapper questionWrapper = new QueryWrapper();
        questionWrapper.eq("scale_id_fk", scaleId);
        List<Question> questions = questionMapper.selectList(questionWrapper);

        if (!CollectionUtils.isEmpty(questions)) {
            List<Long> questionIds = new ArrayList<>();
            questions.stream().forEach(item -> {
                questionIds.add(item.getQuestionId());
            });

            // 删除题目数据
            questionMapper.deleteBatchIds(questionIds);
            // 删除题目选项数据
            QueryWrapper optionWrapper = new QueryWrapper();
            optionWrapper.in("question_id_fk", questionIds);
            optionMapper.delete(optionWrapper);

            // 删除分数数据
            QueryWrapper scoreWrapper = new QueryWrapper();
            scoreWrapper.in("scale_id_fk", scaleId);
            scoreMapper.delete(scoreWrapper);
        }
        //删除计算规则（t_scale_alg）数据
        QueryWrapper scaleAlgWrapper = new QueryWrapper();
        scaleAlgWrapper.eq("scale_id_fk", scaleId);
        scaleAlgMapper.delete(scaleAlgWrapper);

        //删除量表行业（t_scale_project）数据
        QueryWrapper scaleProjectWrapper = new QueryWrapper();
        scaleProjectWrapper.eq("scale_id", scaleId);
        scaleProjectMapper.delete(scaleProjectWrapper);
    }

    @Override
    public void addQuestionAndFactor(List<QuestionVo> questionVoList) {
        List<Option> options = new ArrayList<>();
        questionVoList.stream().forEach(questionVo -> {
            // 题目信息入库
            Question question = new QuestionVo();
            BeanUtils.copyProperties(questionVo, question);
            questionMapper.insert(question);

            // 处理题目选项信息
            if (!CollectionUtils.isEmpty(questionVo.getOptionList())) {
                questionVo.getOptionList().stream().forEach(option -> {
                    option.setQuestionIdFk(question.getQuestionId());
                    options.add(option);
                });
            }

            // 题目因子信息入库
            QuestionFactor questionFactor = new QuestionFactor();
            questionFactor.setQuestionId(question.getQuestionId());
            //如果题目因子信息不为空
            if (null != questionVo.getFactorId()) {
                questionFactor.setFactorId(questionVo.getFactorId());
                questionFactorMapper.insert(questionFactor);
            }
            //如果正反因子信息不为空
            if (null != questionVo.getProAndConFactorId()) {
                questionFactor.setFactorId(questionVo.getProAndConFactorId());
                questionFactorMapper.insert(questionFactor);
            }
        });

        // 选项信息入库
        if (!CollectionUtils.isEmpty(options)) {
            optionServic.saveBatch(options);
        }
    }

    @Override
    public void updateQuestionAndFactor(List<QuestionVo> questionVoList) {
        List<Option> options = new ArrayList<>();
        List<Question> questions = new ArrayList<>();
        questionVoList.stream().forEach(questionVo -> {
            // 更新试题信息
            Question question = new QuestionVo();
            BeanUtils.copyProperties(questionVo, question);
            questions.add(question);
            log.info("题目修改questionVo:[{}]", questionVo.getQuestionId());

            // 处理试题选项信息
            if (!CollectionUtils.isEmpty(questionVo.getOptionList())) {
                questionVo.getOptionList().stream().forEach(option -> {
                    options.add(option);
                });
            }

            //根据题目ID删除之前题目因子关联表的数据
            QueryWrapper<QuestionFactor> questionFactorQueryWrapper = new QueryWrapper<>();
            questionFactorQueryWrapper.eq("question_id", questionVo.getQuestionId());
            questionFactorMapper.delete(questionFactorQueryWrapper);
            //重新添加题目因子关联表
            QuestionFactor questionFactor = new QuestionFactor();
            questionFactor.setQuestionId(question.getQuestionId());
            //如果题目因子信息不为空
            if (null != questionVo.getFactorId()) {
                questionFactor.setFactorId(questionVo.getFactorId());
                questionFactorMapper.insert(questionFactor);
            }
            //如果正反因子信息不为空
            if (null != questionVo.getProAndConFactorId()) {
                questionFactor.setFactorId(questionVo.getProAndConFactorId());
                questionFactorMapper.insert(questionFactor);
            }
        });

        // 更新题目信息
        if (!CollectionUtils.isEmpty(questions)) {
            questionService.saveOrUpdateBatch(questions);
        }
        // 更新选项信息
        if (!CollectionUtils.isEmpty(options)) {
            optionServic.saveOrUpdateBatch(options);
        }
    }

    @Override
    public ScaleScoreVo selectScaleDetail(Long scaleId) {
        ScaleVo scaleVo = scaleMapper.queryDetailById(scaleId);
        ScaleScoreVo scaleScoreVo = new ScaleScoreVo();
        BeanUtils.copyProperties(scaleVo, scaleScoreVo);

        //总分集合
        List<Score> totalList = new ArrayList<>();
        //因子分集合
        List<Score> factorlList = new ArrayList<>();
        //正反分集合
        List<Score> posAndNegList = new ArrayList<>();
        //阴阳分集合
        List<Score> sunAndShadeList = new ArrayList<>();
        List<Score> scoreList = scaleVo.getScoreList();
        //根据因子名去重
        List<Score> finalTotalList = totalList;
        List<Score> finalFactorlList = factorlList;
        List<Score> finalPosAndNegList = posAndNegList;
        List<Score> finalSunAndShadeList = sunAndShadeList;
        scoreList.stream().forEach(score -> {
            if ("总分".equals(score.getAlgType())) {
                finalTotalList.add(score);
            } else if (score.getAlgType().contains("正") || score.getAlgType().contains("反")) {
                finalPosAndNegList.add(score);
            } else if (score.getAlgType().contains("阳") || score.getAlgType().contains("阴")) {
                finalSunAndShadeList.add(score);
            } else {
                finalFactorlList.add(score);
            }

            /*if (score.getAlgType().contains("因子")) {
                finalFactorlList.add(score);
            }*/
        });
        //根据因子名去重
        totalList = totalList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Score::getAlgType))), ArrayList::new));
        scaleScoreVo.setTotalScore(totalList);
        factorlList = factorlList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Score::getAlgType))), ArrayList::new));
        scaleScoreVo.setFactorScore(factorlList);
        posAndNegList = posAndNegList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Score::getAlgType))), ArrayList::new));
        scaleScoreVo.setProAndConScore(posAndNegList);
        sunAndShadeList = sunAndShadeList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Score::getAlgType))), ArrayList::new));
        scaleScoreVo.setLunisolarScore(sunAndShadeList);

        //根据量表id查询计算规则
        CalculationRules calculationRules = new CalculationRules();
        QueryWrapper<ScaleAlg> scaleAlgWrapper = new QueryWrapper<>();
        scaleAlgWrapper.eq("scale_id_fk", scaleId);
        List<ScaleAlg> scaleAlgs = scaleAlgMapper.selectList(scaleAlgWrapper);

        scaleAlgs.stream().forEach(scaleAlg -> {
            if ("总分".equals(scaleAlg.getFactorName())) {
                calculationRules.setTotalScoreRule(scaleAlg.getOperator());
            }
            if ("因子分".equals(scaleAlg.getFactorName())) {
                calculationRules.setFactorScoreRule(scaleAlg.getOperator());
            }
            if ("正反".equals(scaleAlg.getFactorName())) {
                calculationRules.setProAndConScoreRule(scaleAlg.getOperator());
            }
            if ("阴阳".equals(scaleAlg.getFactorName())) {
                calculationRules.setLunisolarScoreRule(scaleAlg.getOperator());
            }
        });
        scaleScoreVo.setCalculationRules(calculationRules);

        return scaleScoreVo;
    }

    /**
     * 添加因子、规则、计算规则
     */
    private void addFactorAndRuleAndCalculationRules(Integer algType, List<Score> scores, Scale scale, ScaleAlg scaleAlg, ScaleScoreVo scaleScoreVo) {
        //计算规则
        CalculationRules calculationRules = scaleScoreVo.getCalculationRules();

        QueryWrapper<Alg> algQueryWrapper = new QueryWrapper<>();
        if (Constants.TOTAL_SCORE_TYPE.equals(algType)) {
            algQueryWrapper.eq("alg_name", "总分");
            //计算规则
            scaleAlg.setFactorName("总分");
            if (null != calculationRules) {
                scaleAlg.setOperator(calculationRules.getTotalScoreRule());
            } else {
                scaleAlg.setOperator(null);
            }
        } else if (Constants.FACTOR_SCORE_TYPE.equals(algType)) {
            algQueryWrapper.eq("alg_name", "因子分");
            scaleAlg.setFactorName("因子分");
            if (null != calculationRules) {
                scaleAlg.setOperator(calculationRules.getFactorScoreRule());
            } else {
                scaleAlg.setOperator(null);
            }
        } else if (Constants.POSITIVE_AND_NEGATIVE_SCORE_TYPE.equals(algType)) {
            algQueryWrapper.eq("alg_name", "正反");
            scaleAlg.setFactorName("正反");
            if (null != calculationRules) {
                scaleAlg.setOperator(calculationRules.getProAndConScoreRule());
            } else {
                scaleAlg.setOperator(null);
            }
        } else {
            algQueryWrapper.eq("alg_name", "阴阳");
            scaleAlg.setFactorName("阴阳");
            if (null != calculationRules) {
                scaleAlg.setOperator(calculationRules.getLunisolarScoreRule());
            } else {
                scaleAlg.setOperator(null);
            }
        }
        //查出算法ID
        Alg alg = algMapper.selectOne(algQueryWrapper);

        scaleAlg.setScaleIdFk(scale.getScaleId());
        scaleAlg.setAlgIdFk(alg.getAlgId());
        //添加计算规则
        scaleAlgMapper.insert(scaleAlg);

        //添加因子和规则
        addFactorAndRule(scores, alg, scale);
    }

    /**
     * 添加因子、规则
     */
    private void addFactorAndRule(List<Score> scores, Alg alg, Scale scale) {
        //添加因子和规则
        Factor factor = new Factor();
        if (!CollectionUtils.isEmpty(scores)) {
            scores.stream().forEach(score -> {
                //添加因子之前判断一下是否有该因子
                QueryWrapper<Factor> factorQueryWrapper = new QueryWrapper<>();
                factorQueryWrapper.eq("factor_name", score.getAlgType());
                Factor factorOrigin = factorMapper.selectOne(factorQueryWrapper);
                if (null == factorOrigin) {
                    //添加到因子表 返回因子id
                    factor.setFactorName(score.getAlgType());
                    factor.setCreateTime(new Date());
                    factor.setUpdateTime(new Date());
                    factor.setAlgIdFk(alg.getAlgId());
                    //添加因子
                    factorMapper.addFactor(factor);

                    score.setFactorIdFk(factor.getFactorId());
                    log.info("factorId:[{}]", factor.getFactorId());
                } else {
                    log.info("factorId:[{}]", factorOrigin.getFactorId());
                    score.setFactorIdFk(factorOrigin.getFactorId());
                }
                score.setAlgType(score.getAlgType());
                score.setScaleIdFk(scale.getScaleId());
                scoreMapper.insert(score);
            });
        }
    }
}
